package com.common.www.utils;

import org.apache.commons.codec.binary.Base64;
import org.springframework.web.multipart.MultipartFile;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

import javax.imageio.ImageIO;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


public class Base64Utils {
    /**
     * 图片转化成base64字符串
     *
     * @param imgPath
     * @return
     */
    public static String getImageBase64(String imgPath) {// 将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        String imgFile = imgPath;// 待处理的图片
        InputStream in = null;
        byte[] data = null;
        String encode = null; // 返回Base64编码过的字节数组字符串
        // 对字节数组Base64编码
        BASE64Encoder encoder = new BASE64Encoder();
        try {
            // 读取图片字节数组
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            encode = encoder.encode(data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return encode;
    }

    /**
     * base64字符串转化成图片
     *
     * @param base64      图片编码
     * @param imgFilePath 存放到本地路径
     * @return
     * @throws IOException
     */
    @SuppressWarnings("finally")
    public static boolean generateImage(String base64, String imgFilePath) throws IOException { // 对字节数组字符串进行Base64解码并生成图片
        if (base64 == null) // 图像数据为空
            return false;
        // 去掉base64前缀 data:image/jpeg;base64,
        if (base64.contains("data:image/")) {
            base64 = base64.substring(base64.indexOf(",", 1) + 1, base64.length());
        }

        BASE64Decoder decoder = new BASE64Decoder();
        OutputStream out = null;
        try {
            out = new FileOutputStream(imgFilePath);
            // Base64解码
            byte[] b = decoder.decodeBuffer(base64);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据
                    b[i] += 256;
                }
            }
            out.write(b);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            out.flush();
            out.close();
            return true;
        }

//        // 解密
//        try {
//            // 解密
//            Base64.Decoder decoder = Base64.getDecoder();
//            // 去掉base64前缀 data:image/jpeg;base64,
//            base64 = base64.substring(base64.indexOf(",", 1) + 1, base64.length());
//            byte[] b = decoder.decode(base64);
//            // 处理数据
//            for (int i = 0; i < b.length; ++i) {
//                if (b[i] < 0) {
//                    b[i] += 256;
//                }
//            }
//            // 保存图片
//            OutputStream out = new FileOutputStream(imgFilePath);
//            out.write(b);
//            out.flush();
//            out.close();
//            // 返回图片的相对路径 = 图片分类路径+图片名+图片后缀
//            return true;
//        } catch (IOException e) {
//            return false;
//        }
    }

    /**
     * 得到base64图片文件的后缀格式
     */
    public static String getBaseStrSuffix(String base64) {
        int index = base64.indexOf("data:image/");
        int index2 = base64.indexOf(";base64");
        String suffix = "jpg";
        if (index >= 0 && index2 >= 0) {
            suffix = base64.substring(index + 11, index2);
        }
        return suffix;
    }


    /**
     * BufferedImage 编码转换为 base64
     *
     * @param bufferedImage
     * @param suffix        后缀支持jpg和png
     * @return
     */
    public static String BufferedImageToBase64(BufferedImage bufferedImage, String suffix) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
        try {
            ImageIO.write(bufferedImage, "png", baos);//写入流中
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] bytes = baos.toByteArray();//转换成字节
        BASE64Encoder encoder = new BASE64Encoder();
        String png_base64 = encoder.encodeBuffer(bytes).trim();//转换成base64串
        png_base64 = png_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
//        System.out.println("值为：" + "data:image/jpg;base64," + png_base64);
        return "data:image/" + suffix + ";base64," + png_base64;
    }

    /**
     * base64 编码转换为 BufferedImage
     *
     * @param base64
     * @return
     */
    public static BufferedImage base64ToBufferedImage(String base64) {
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] bytes1 = decoder.decodeBuffer(base64);
            ByteArrayInputStream bais = new ByteArrayInputStream(bytes1);
            return ImageIO.read(bais);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 直接转base64
     */
    public String getBase64String(MultipartFile multiPartFile) throws IOException {
        String baseStr = null;
        BASE64Encoder encoder = new BASE64Encoder();
        baseStr = encoder.encode(multiPartFile.getBytes());
        baseStr = baseStr.replaceAll("\r\n", "");
        return baseStr;
    }

    /**
     * 字节数组转Base64编码
     */
    public static String byteToBase64(byte[] bytes) {
//        BASE64Encoder encoder = new BASE64Encoder();
//        return encoder.encode(bytes);
        return new String(Base64.encodeBase64(bytes));
    }


    /**
     * Base64编码转字节数组
     */
    public static byte[] base64ToByte(String base64Key) throws IOException {
//        BASE64Decoder base64Decoder = new BASE64Decoder();
//        return base64Decoder.decodeBuffer(base64Key);
        return Base64.decodeBase64(base64Key);
    }

    /**
     * 文本桩base64
     */
    public static String textToBase64(String text) {
        return new String(byteToBase64(text.getBytes()));
    }

    public static String decodeString(String encoded) {
        // 对Base64编码的字符串进行解码
        byte[] decodedBytes = java.util.Base64.getDecoder().decode(encoded);
        // 将字节数组转换回字符串
        String decoded = new String(decodedBytes, StandardCharsets.UTF_8);
        return decoded;
    }


}